/**
 * Created by ptt on 2016/5/27/0027.
 */
define(["../maintools/Model.js", "../../gis/gis/loadMap.js"], function (Model, map) {
    var map = map.map;
    //专题图类型数据结构
    var statistical = [
        {
            index: 1,
            total: 6,
            title: "规划成果",
            content: ["规划分布"],
            url: mapURL.szRoadGh,
            condition:
                {
                    "规划分布": {
                        "years": [2013, 2014, 2015, 2016]
                    }
                },
            baseUrl: {
                "规划分布": [mapURL.szghWmsUrl, "szgh:szgh_layergroup"]
            },
            queryName: {
                "规划分布": "projectnam"
            },
            layer: {
                "规划分布": "TileWMS"
            },
            hover: {
                "规划分布": ""
            },
            detailpage: {
                "规划分布": ""
            }
        },
        {
            index: 2,
            total: 6,
            title: "建设项目",
            content: ["前期项目分布", "在建项目分布 "],
            url: "",
            condition:
                {
                    "前期项目分布": {
                        "years": [2013, 2014, 2015, 2016]
                    },
                    "在建项目分布 ": {
                        "years": [2013, 2014, 2015, 2016]
                    }
                },
            baseUrl: {
                "前期项目分布": ["/ssjc/pre/preparepoj!getGeoJsonByYear.action?", "/ssjc/images/gis/marker-ghduzd.png"],
                "在建项目分布 ": ["/ssjc/mp/project!getGeoJsonByYear.action?", "/ssjc/images/gis/marker-ghduzd.png"]
            },
            queryName: {
                "前期项目分布": "",
                "在建项目分布 ": ""
            },
            layer: {
                "前期项目分布": "Vector",
                "在建项目分布 ": "Vector"
            },
            hover: {
                "前期项目分布": "/ssjc/images/gis/marker.png",
                "在建项目分布 ": "/ssjc/images/gis/marker.png"
            },
            detailpage: {
                "前期项目分布": "/ssjc/pre/view/preparepoj!view.action?id=",
                "在建项目分布 ": "/ssjc/mp/view/project!view.action?id="
            }
        },
        {
            index: 3,
            total: 6,
            title: "道路基础路网",
            content: ["路网统计", "路网密度", "道路网分布", "桥梁分布", "桥梁辖区统计", "隧道分布"],
            url: mapURL.szRoadurl,
            condition:
                {
                    "路网统计": {
                        "type": ["市政道路", "公路"],
                        "fromParam": ["道路长度", "道路面积", "道路数量"]
                    },
                    "路网密度": {
                    },
                    "道路网分布": {
                        "type": ["市政道路", "公路"]
                    },
                    "桥梁分布": {
                        "selector": ["城市桥梁", "公路桥梁"]
                    },
                    "桥梁辖区统计": {
                        "years": [2013, 2014, 2015, 2016]
                    },
                    "隧道分布": {
                    }
                },
            baseUrl: {
                "路网统计": ["/ssjc/taglib/roadbasicinfo!showAllDistrict.action?", ""],
                "路网密度": ["/ssjc/dl/roadbasicinfo!getLw.action",""],
                "道路网分布": [mapURL.tgisRoadWfsUrl, ""],
                "桥梁分布": [mapURL.tgisWmsUrl, "gist:道路设施"],
                "桥梁辖区统计": ["/ssjc/qlyhtj/bridgedetection!gisCountJson.action?", ""],
                "隧道分布": [mapURL.tgisWmsUrl, "gist:道路设施_隧道"]
            },
            queryName: {
                "路网统计": "",
                "路网密度": "",
                "道路网分布": "NAME",
                "桥梁分布": "名称",
                "桥梁辖区统计": "",
                "隧道分布": "道路名称"
            },
            layer: {
                "路网统计": "overlay",
                "路网密度": "overlay",
                "道路网分布": "WFS",
                "桥梁分布": "TileWMS",
                "桥梁辖区统计": "overlay",
                "隧道分布": "TileWMS"
            },
            hover: {
                "路网统计": "",
                "路网密度": "",
                "道路网分布": "",
                "桥梁分布": "",
                "桥梁辖区统计": "",
                "隧道分布": ""
            },
            detailpage: {
                "路网统计": "",
                "路网密度": "",
                "道路网分布": "/ssjc/gis/lifecycle.jsp?roadname=",
                "桥梁分布": "",
                "桥梁辖区统计": "",
                "隧道分布": ""
            }
        },
        {
            index: 4,
            total: 6,
            title: "路况监测",
            content: ["路况分布", "各辖区统计图"],
            url: mapURL.szPciurl,
            condition:
                {
                    "路况分布": {
                        "years": [2013, 2014, 2015, 2016],
                        "type": ["市政道路", "公路"],
                        "kpi-101": ["MQI", "PCI", "RQI", "SCI", "PQI", "TCI"],
                        "kpi-102": ["PQI", "RQI", "PCI", "FQI", "FCI", "RZ", "CL", "PL", "SDL", "QL"]
                    },
                    "各辖区统计图": {
                        "years": [2013, 2014, 2015, 2016],
                        "type": ["市政道路", "公路"],
                        "kpi-101": ["MQI", "PCI", "RQI", "SCI", "PQI", "TCI"],
                        "kpi-102": ["PQI", "RQI", "PCI", "FQI", "FCI", "RZ", "CL", "PL", "SDL", "QL"]
                    }
                },
            baseUrl: {
                "路况分布": [mapURL.tgisRoadWfsUrl, "/ssjc/lj/detectioninfo!gisGradeJson.action?"],
                "各辖区统计图": ["/ssjc/lj/detectioninfo!gisCountJson.action?", ""]
            },
            queryName: {
                "路况分布": "",
                "各辖区统计图": ""
            },
            layer: {
                "路况分布": "WFS",
                "各辖区统计图": "overlay"
            },
            hover: {
                "路况分布": "",
                "各辖区统计图": ""
            },
            detailpage: {
                "路况分布": "/ssjc/gis/lifecycle.jsp?roadname=",
                "各辖区统计图": ""
            }
        },
        {
            index: 5,
            total: 6,
            title: "日常养护",
            content: ["养护区域分布", "巡查轨迹", "病害分布", "保养分布", "小修项目分布", "三危地图","养护处置统计"],
            url: mapURL.szRoadbh,
            condition:
                {
                    "养护区域分布": {

                    },
                    "巡查轨迹": {
                        "sYears": [2013, 2014, 2015, 2016],
                        "sMonth": "true",
                        "sDay": "true",
                        "eYears": [2013, 2014, 2015, 2016],
                        "eMonth": "true",
                        "eDay": "true"
                    },
                    "病害分布": {
                        "sYears": [2013, 2014, 2015, 2016],
                        "sMonth": "true",
                        "sDay": "true",
                        "eYears": [2013, 2014, 2015, 2016],
                        "eMonth": "true",
                        "eDay": "true"
                    },
                    "保养分布": {
                        "sYears": [2013, 2014, 2015, 2016],
                        "sMonth": "true",
                        "sDay": "true",
                        "eYears": [2013, 2014, 2015, 2016],
                        "eMonth": "true",
                        "eDay": "true"
                    },
                    "小修项目分布": {
                        "sYears": [2013, 2014, 2015, 2016],
                        "sMonth": "true",
                        "sDay": "true",
                        "eYears": [2013, 2014, 2015, 2016],
                        "eMonth": "true",
                        "eDay": "true"
                    },
                    "三危地图": {
                        "sYears": [2013, 2014, 2015, 2016],
                        "sMonth": "true",
                        "sDay": "true",
                        "eYears": [2013, 2014, 2015, 2016],
                        "eMonth": "true",
                        "eDay": "true"
                    },
                    "养护处置统计":{
                        "sYears": [2013, 2014, 2015, 2016],
                        "sMonth": "true",
                        "sDay": "true",
                        "eYears": [2013, 2014, 2015, 2016],
                        "eMonth": "true",
                        "eDay": "true",
                        "fromParam": ["验收率", "巡查达标率", "主动发现率","处置完成率"]
                    }
                },
            baseUrl: {
                "养护区域分布": [mapURL.szyhbdWmsUrl, "yhbd:szyhbd"],
                "巡查轨迹": ["/ssjc/rep/tracking!provideGeoJson.action?", "/ssjc/images/gis/path.png"],
                "病害分布": ["/ssjc/rep/damagedisease!provideGeoJson.action?", "/ssjc/images/gis/disease.png"],
                "保养分布": ["/ssjc/rep/roadfit!provideGeoJson.action?", "/ssjc/images/gis/maintain.png"],
                "小修项目分布": ["/ssjc/rep/roadrepair!provideGeoJson.action?", "/ssjc/images/gis/minorrepair.png"],
                "三危地图": ["/ssjc/em/facilitykey!provideGeoJson.action?", "/ssjc/images/gis/sanwei.png"],
                "养护处置统计":["/ssjc/statistic/statistic!getSData.action?",""]
            },
            queryName: {
                "养护区域分布": "bdname",
                "巡查轨迹": "trajectory", //轨迹标志
                "病害分布": "",
                "保养分布": "",
                "小修项目分布": appConfig.repairAddress+"/rep/roadrepairaccept!getRepairAccept.action?flag=1&num=1&roadRepairID=",
                "三危地图": "",
                "养护处置统计":""
            },
            layer: {
                "养护区域分布": "TileWMS",
                "巡查轨迹": "Vector",
                "病害分布": "Vector",
                "保养分布": "Vector",
                "小修项目分布": "Vector",
                "三危地图": "Vector",
                "养护处置统计":"overlay"
            },
            hover: {
                "养护区域分布": "",
                "巡查轨迹": "/ssjc/images/gis/path-red.png",
                "病害分布": "/ssjc/images/gis/disease-red.png",
                "保养分布": "/ssjc/images/gis/maintain-red.png",
                "小修项目分布": "/ssjc/images/gis/minorrepair-red.png",
                "三危地图": "/ssjc/images/gis/sanwei-red.png",
                "养护处置统计":""
            },
            detailpage: {
                "养护区域分布": "",
                "巡查轨迹": "/ssjc/rep/tracking!provideGeoJsonLine.action?userId=",
                "病害分布": appConfig.repairAddress+"/inspection/damagedisease!getDetail.action?caseNo=",
                "保养分布": appConfig.repairAddress+"/fit/roadfit!info.action?id=",
                "小修项目分布": appConfig.repairAddress+"/rep/roadrepairapply!input.action?hd=0&type=1&num=0&roadRepairID=",
                "三危地图": "",
                "养护处置统计":""
            }
        },
        {
            index: 6,
            total: 6,
            title: "大中修项目",
            content: ["在建项目分布"],
            url: "",
            condition:
                {
                    "在建项目分布": {
                        "years": [2013, 2014, 2015, 2016]
                    }
                },
            baseUrl: {
                "在建项目分布": ["/ssjc/yh/maintenance!getGeoJsonByYear.action?", "/ssjc/images/gis/marker-ghduzd.png"]
            },
            queryName: {
                "在建项目分布": ""
            },
            layer: {
                "在建项目分布": "Vector"
            },
            hover: {
                "在建项目分布": "/ssjc/images/gis/marker.png"
            },
            detailpage: {
                "在建项目分布": "/ssjc/yh/view/maintenance!view.action?id="
            }
        }
    ];

    function access(data, model, map) {
        var layer;
        var source;
        switch (data.layer) {
            case "Vector" : {
                var image = new ol.style.Icon({
                    src: data.query,
                    scale: 0.8
                });
                var styles = {
                    'Point': new ol.style.Style({
                        image: image
                    }),
                    'LineString': new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#CD00CD',
                            width: 4
                        })
                    }),
                    'Polygon': new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'blue',
                            lineDash: [4],
                            width: 4
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(0, 0, 255, 0.1)'
                        })
                    })
                };
                var styleFunction = function(feature) {
                    return styles[feature.getGeometry().getType()];
                };

                var vectorSource = new ol.source.Vector();
                var value = data.value;
                var url;
                if (value.years) {
                    url = data.url+"year="+value.years;
                } else {
                    url = data.url + "beginTime=" + value.sYears + "-" + value.sMonth + "-" + value.sDay + "&endTime=" + value.eYears + "-" + value.eMonth + "-" + value.eDay;
                }
                $.get(url).
                   then(function(response) {
                    var format = new ol.format.GeoJSON();
                    var features;
                    if(value.years)
                    {
                        if(response.length>0)
                        {
                            for(var i=0;i<response.length;i++)
                            {
                                //存在则添加
                                if(response[i]) {
                                    features = format.readFeatures(response[i]);
                                    vectorSource.addFeatures(features);
                                }
                            }
                        }
                    }
                    else
                    {
                        features = format.readFeatures(response, {featureProjection: 'EPSG:3857'});
                        vectorSource.addFeatures(features);
                    }
                        layer = new ol.layer.Vector({
                            source: vectorSource,
                            style: styleFunction
                        });
                        model.layer = layer;
                        map.addLayer(layer);
                        var selectClick = new ol.interaction.Select({
                            condition: ol.events.condition.click
                        });
                        var selectPointerMove = new ol.interaction.Select({
                            condition: ol.events.condition.pointerMove
                        });
                        model.selectClick = selectClick;
                        model.selectPointerMove = selectPointerMove;
                        map.addInteraction(selectClick);
                        map.addInteraction(selectPointerMove);

                        selectClick.on("select", function (e) {
                            if (!e.target.getFeatures().getLength()) return $("#overlay").data("query").setPosition([9999, 9999]);
                            var overlay = new ol.Overlay({
                            element: document.getElementById("overlay"),
                            positioning: "bottom-center"
                        });
                            map.addOverlay(overlay);
                            var element = overlay.getElement();
                            $(element).addClass("detail");
                            $(element).find(".ohead p").html(e.target.getFeatures().array_[0].values_.landmark);
                            $(element).find(".ocontent").empty();
                            var property = e.target.getFeatures().array_[0].getProperties();
                            for (var key in property) {
                                if (typeof property[key] === "string" && key !== "landmark" && key !== "id"&&key!="userId"&&key!="projectId")
                                $("<p>").text(Pengtu.buildCodeName("7777", key)+ ": " + property[key]).appendTo($(element).find(".ocontent"));
                            }
                            if(data.queryName){
                                if(data.queryName==="trajectory") {
                                    $("<p>").text("巡查轨迹:").append($("<a>").text("轨迹回放").attr({
                                        "href": data.detail + property["userId"],
                                        "target": "_blank"
                                    })).appendTo($(element).find(".ocontent"));
                                    $(element).data("query", overlay);
                                }
                                else { //小修
                                    $("<p>").text("申报表:").append($("<a>").text("查看申报表").attr({
                                        "href": data.detail + property["id"],
                                        "target": "_blank"
                                    })).appendTo($(element).find(".ocontent"));
                                    $("<p>").text("  验收表:").append($("<a>").text("查看验收表").attr({
                                        "href": data.queryName + property["id"],
                                        "target": "_blank"
                                    })).appendTo($(element).find(".ocontent"));
                                    $(element).data("query", overlay);
                                }
                            }
                            else if(property.id) {
                                $("<p>").text("详细信息:").append($("<a>").text("查看详情").attr({
                                    "href": data.detail + property["id"],
                                    "target": "_blank"
                                })).appendTo($(element).find(".ocontent"));
                                $(element).data("query", overlay);
                            }
                            else if(property.projectId){
                                $("<p>").text("详细信息:").append($("<a>").text("查看详情").attr({
                                    "href": data.detail + property["projectId"],
                                    "target": "_blank"
                                })).appendTo($(element).find(".ocontent"));
                                $(element).data("query", overlay);
                            }
                            $(element).data("query", overlay);
                            overlay.setPosition(e.mapBrowserEvent.coordinate);
                            var pixel = e.mapBrowserEvent.pixel;

                            var maxWidth = $("#mapContain").prop("clientWidth") - 200;
                            if (pixel[0] < 200 || pixel[0] > maxWidth || pixel[1] < 200) {
                                var coordinate;
                                var pan = new ol.animation.pan({
                                    duration: 800,
                                    easing: ol.easing.easeOut,
                                    source: map.getView().getCenter()
                                });
                                map.beforeRender(pan);
                                if (pixel[0] > maxWidth) {
                                    coordinate = map.getCoordinateFromPixel([$("#mapContain").prop("clientWidth") / 2 + 200, pixel[1]]);
                                    map.getView().setCenter(coordinate);
                                } else if (pixel[0] < 200) {
                                    coordinate = map.getCoordinateFromPixel([$("#mapContain").prop("clientWidth") / 2 - 200, pixel[1]]);
                                    map.getView().setCenter(coordinate);
                                } else if (pixel[1] < 200){
                                    coordinate = map.getCoordinateFromPixel([pixel[0], $("#mapContain").prop("clientHeight") / 2 - 200]);
                                    map.getView().setCenter(coordinate);
                                } else {
                                    map.getView().setCenter(e.mapBrowserEvent.coordinate);
                                }
                            }
                        });

                        var image_hover = new ol.style.Icon({
                            src: data.symbol,
                            scale: 0.8
                        });
                        var style_hover = {
                        'Point': new ol.style.Style({
                            image: image_hover
                        }),
                        'LineString': new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: '#00FF00',
                                width: 4
                            })
                        }),
                        'Polygon': new ol.style.Style({
                            stroke: new ol.style.Stroke({
                                color: '#00FF00',
                                lineDash: [4],
                                width: 4
                            }),
                            fill: new ol.style.Fill({
                                color: 'rgba(0, 0, 255, 0.1)'
                            })
                        })
                    };
                        var pre;
                        selectPointerMove.on("select", function(e) {
                            var hit = !!e.target.getFeatures().getLength();
                            map.getTargetElement().style.cursor = hit ? 'pointer' : 'default';
                            if (hit) {
                                pre && pre.setStyle(styles[pre.getGeometry().getType()]);
                                pre = e.target.getFeatures().array_[0];
                                pre.setStyle(style_hover[pre.getGeometry().getType()]);
                            } else {
                                pre && pre.setStyle(styles[pre.getGeometry().getType()]);
                            }
                        });

                        Message_bone.trigger("infoEnd");
                        model.buttonStat = {
                            "klass": "remove",
                            "text": "移除"
                        };
                        Message_bone.trigger("loaded");
                    });

                Message_bone.trigger("infoStart");

                model.buttonStat = {
                    "klass": "loading",
                    "text": "加载中"
                };
                Message_bone.trigger("loading");
                break;
            }
            case "TileWMS": {
                var LAYERS = data.value["selector"] ? data.query + '_' + data.value["selector"]
                    : data.query;
                source = new ol.source.TileWMS({
                    url: data.url,
                    params: {
                        LAYERS: LAYERS,
                        STYLES: '',
                        format: 'image/png',
                        tiled: true,
                        transparent: true,
                        VERSION: "1.1.1",
                        SRS: "EPSG:900913"
                    },
                    crossOrigin:"anonymous"
                });
                var tile_loading = 0, tile_loaded = 0,flag = true;
                source.once("tileloadstart", function (e) {
                    ++tile_loading;
                    if (flag) {
                        Message_bone.trigger("infoStart");

                        model.buttonStat = {
                            "klass": "loading",
                            "text": "加载中"
                        };
                        Message_bone.trigger("loading");
                        flag = false;
                    }
                });
                source.once("tileloadend", function (e) {
                    ++tile_loaded;
                    if (tile_loading === tile_loaded) {
                        Message_bone.trigger("infoEnd");

                        model.buttonStat = {
                            "klass": "remove",
                            "text": "移除"
                        };
                        Message_bone.trigger("loaded");
                        flag = true;
                    }
                });
                layer = new ol.layer.Tile({
                    source: source
                });
                model.layer = layer;
                map.addLayer(layer);
                Message_bone.trigger("query", data);
                break;
            }
            case "overlay": {
                Message_bone.trigger("infoStart");

                model.buttonStat = {
                    "klass": "loading",
                    "text": "加载中"
                };
                Message_bone.trigger("loading");
                var overlays = [];
                url = data.url;
                if(data.value.sYears){
                    url = data.url + "beginTime=" + data.value.sYears + "-" + data.value.sMonth + "-" + data.value.sDay + "&endTime=" +data. value.eYears + "-" + data.value.eMonth + "-" + data.value.eDay+"&";
                    url += mapp[data.value.fromParam] ? "fromParam=" + mapp[data.value.fromParam] + "&" : "";
                }
                else {
                    url += mapp[data.value.fromParam] ? "fromParam=" + mapp[data.value.fromParam] + "&" : "";
                    url += mapp[data.value.type] ? "type=" + mapp[data.value.type] + "&" : "";
                    url += data.value.years ? "year=" + data.value.years + "&" : "";
                    url += data.value.kpi ? "target=" + data.value.kpi + "&" : "";
                }
                $.get(url).then(function (response) {
                    var color = ['#E54912','#DD7C6A','#497B36','#42BABC','#F4BE29','#BCBE48','#B5DBBA','#ABB7D0','#8595CA','#D7A2C6','#00000'];
                    var length = response.length;
                    var overlay;
                    model.lagendRenderdata = [];
                    if (!length) {
                        Message_bone.trigger("infoEnd");
                        model.buttonStat = {
                            "klass": "confirm",
                            "text": "查看"
                        };
                        Message_bone.trigger("removeLayer");
                    }
                    for (var i = 0; i < length; i += 1) {
                        overlay = new ol.Overlay({
                            element: $('<div class="popupoverlay" style="width: 150px; height: 150px">')[0],
                            positioning: "center-center"
                        });
                        var datas = [],
                            charts = chartsType[data.value.charts],
                            rdata = response[i].data,
                            len = rdata.length;
                        for (var j = 0; j < len; j +=1) {
                            datas.push({
                                value: rdata[j],
                                name: response[i].legend[j]
                            });
                            if (!model.lagendRenderdata.finish) {
                                model.lagendRenderdata.push({
                                    color: color[j],
                                    text: response[i].legend[j]
                                });
                            }
                        }
                        model.lagendRenderdata.finish = true;
                        var div = overlay.getElement();
                        var myChart = echarts.init(div);
                        var Chartunit=response[i].subtitle=="百分比"?"%":response[i].subtitle;
                        var centerName=response[i].density? response[i].density +'\n'+response[i].name:response[i].name;
                        if (data.content === '各辖区统计图') {
                            option = {
                                color: color,
                                series: [
                                    {
                                        name: centerName + '\n' + response[i].legend[0] + '\n' + response[i].data[0] + Chartunit,
                                        type: "pie",
                                        radius: ['50%', '70%'],
                                        center: ['50%', '50%'],
                                        data: datas,
                                        avoidLabelOverlap: false,
                                        label: {
                                            normal: {
                                                show: true,
                                                position: 'center',
                                                formatter: "{a}",
                                                textStyle: {
                                                    fontSize: '15',
                                                    fontWeight: 'bold',
                                                    color: "#3E4058"
                                                }
                                            }
                                        },
                                        labelLine: {
                                            normal: {
                                                show: false
                                            }
                                        }
                                    }
                                ]
                            };
                        } else {
                            option = {
                                tooltip: {
                                    trigger: 'item',
                                    formatter: "{b}: {c} " + Chartunit
                                },
                                color: color,
                                series: [
                                    {
                                        name: centerName,
                                        type: "pie",
                                        radius: ['50%', '70%'],
                                        center: ['50%', '50%'],
                                        data: datas,
                                        avoidLabelOverlap: false,
                                        label: {
                                            normal: {
                                                show: true,
                                                position: 'center',
                                                formatter: "{a}",
                                                textStyle: {
                                                    fontSize: '15',
                                                    fontWeight: 'bold',
                                                    color: "#3E4058"
                                                }
                                            },
                                            emphasis: {
                                                show: true,
                                                textStyle: {
                                                    fontSize: '15',
                                                    fontWeight: 'bold',
                                                    color: "#3E4058"
                                                }
                                            }
                                        },
                                        labelLine: {
                                            normal: {
                                                show: false
                                            }
                                        }
                                    }
                                ]
                            };
                        }
                        if (charts === "bar" || charts === "line") {
                            option.xAxis = {
                                data: response[i].legend
                            };
                            option.yAxis = {};
                            option.series = [
                                {
                                    name: response[i].name,
                                    type: charts,
                                    data:datas,
                                    width: "100%",
                                    height: "100%",
                                    itemStyle: {
                                        normal: {
                                            label: {
                                                show: false
                                            }
                                        }
                                    }
                                }
                            ]
                        }
                        myChart.setOption(option);
                        $(div).on("mousedown", "canvas", function (e) {
                            var view = map.getView();
                            var xy = map.getCoordinateFromPixel([e.clientX, e.clientY]);
                            $(document).on("mousemove", function (e) {
                                var newPoint = map.getCoordinateFromPixel([e.clientX, e.clientY]);
                                var coorsub = [(newPoint[0] - xy[0]) / 10, (newPoint[1] - xy[1]) / 10];
                                var center = view.getCenter();
                                newCenter = [center[0] - coorsub[0], center[1] - coorsub[1]];
                                view.setCenter(newCenter);
                            });
                            $(document).on("mouseup", function (e) {
                                $(this).off("mousemove");
                            });
                        });
                        $(div).on("mousewheel", "canvas", function (e) {
                            var view = map.getView();
                            var scroll = e.originalEvent.wheelDelta ?
                                e.originalEvent.wheelDelta > 0 ? 1 : -1
                                : e.originalEvent.detail > 0 ? -1 : 1;
                            var zoom = ol.animation.zoom({
                                resolution: view.getResolution(),
                                duration: 400
                            });
                            map.beforeRender(zoom);
                            view.setZoom(view.getZoom() + scroll);

                        });
                        overlay.setPosition(ol.proj.transform(districkcentre[response[i].code], 'EPSG:4326', 'EPSG:3857'));
                        overlays.push(overlay);
                        model.layer = overlays;
                        map.addOverlay(overlay);
                    }
                    var zoom = ol.animation.zoom({
                        resolution: map.getView().getResolution(),
                        duration: 400
                    });
                    data.content !== '各辖区统计图' && Message_bone.trigger("legendShow", [model.lagendRenderdata]);
                    map.beforeRender(zoom);
                    map.getView().setZoom(11);
                    map.getLayers().getArray()[0].setOpacity("0.7");
                    Message_bone.trigger("infoEnd");
                    model.buttonStat = {
                        "klass": "remove",
                        "text": "移除"
                    };
                    Message_bone.trigger("loaded");
                });
                break;
            }
            case "WFS": {
                Message_bone.trigger("infoStart");
                model.buttonStat = {
                    "klass": "loading",
                    "text": "加载中"
                };
                Message_bone.trigger("loading");

                source = new ol.source.Vector();
                layer = new ol.layer.Vector({
                    source: source,
                    style:data.query?evaluationStyleFun:WfsstyleFunction
                });
                //获取路况等级
                if(data.query)
                {
                       var evaluationUrl=data.query+"year="+data.value.years+"&target="+data.value.kpi+"&type="+mapp[data.value.type];
                    $.get(evaluationUrl).
                    then(function(response){
                        evaluationdata=response;
                        });
                }
                var f = ol.format.ogc.filter;
                var featureRequest = new ol.format.WFS().writeGetFeature({
                    srsName: 'EPSG:4326',
                    featureNS: 'http://192.168.0.50:9898/szroad',
                    featurePrefix: 'szroad',
                    featureTypes: ['ptroad'],
                    outputFormat: 'application/json',
                    filter: f.equalTo('cityrode', data.value.type)
                });
                // post请求，并根据请求的数据进行加载
                fetch(data.url, {
                    method: 'POST',
                    body: new XMLSerializer().serializeToString(featureRequest)
                }).then(function(response) {
                    return response.json();
                }).then(function(json) {
                    var features = new ol.format.GeoJSON().readFeatures(json,{featureProjection: 'EPSG:3857'});
                    source.addFeatures(features);
                });
                source.once("addfeature", function(e) {
                    Message_bone.trigger("infoEnd");
                    model.buttonStat = {
                        "klass": "remove",
                        "text": "移除"
                    };
                    Message_bone.trigger("loaded");
                });
                model.layer = layer;
                map.addLayer(layer);
                //添加点击选择事件
                var selectClick = new ol.interaction.Select({
                    condition: ol.events.condition.click
                });
                var selectPointerMove = new ol.interaction.Select({
                    condition: ol.events.condition.pointerMove
                });
                model.selectClick = selectClick;
                model.selectPointerMove = selectPointerMove;
                map.addInteraction(selectClick);
                map.addInteraction(selectPointerMove);
                selectClick.on("select", function (e) {
                    if (!e.target.getFeatures().getLength()) return $("#overlay").data("query").setPosition([9999, 9999]);
                    var overlay = new ol.Overlay({
                        element: document.getElementById("overlay"),
                        positioning: "bottom-center"
                    });
                    map.addOverlay(overlay);
                    var element = overlay.getElement();
                    $(element).addClass("detail");
                    $(element).find(".ohead p").html(e.target.getFeatures().array_[0].values_.name);
                    $(element).find(".ocontent").empty();
                    var property = e.target.getFeatures().array_[0].getProperties();
                    for (var key in property) {
                        if (typeof property[key] === "string" &&(
                            key === "rode_type"||key==="street"||key==="class"))
                      $("<p>").text(Pengtu.buildCodeName("7777", key)+ ": " + property[key]).appendTo($(element).find(".ocontent"));
                    }
                    $("<p>").text("详细信息:").append($("<a>").text("生命周期").attr({
                        "href": data.detail + property["name"],
                        "target": "_blank"
                    })).appendTo($(element).find(".ocontent"));

                    $(element).data("query", overlay);
                    overlay.setPosition(e.mapBrowserEvent.coordinate);
                    var pixel = e.mapBrowserEvent.pixel;
                    var maxWidth = $("#mapContain").prop("clientWidth") - 200;
                    if (pixel[0] < 200 || pixel[0] > maxWidth || pixel[1] < 200) {
                        var coordinate;
                        var pan = new ol.animation.pan({
                            duration: 800,
                            easing: ol.easing.easeOut,
                            source: map.getView().getCenter()
                        });
                        map.beforeRender(pan);
                        if (pixel[0] > maxWidth) {
                            coordinate = map.getCoordinateFromPixel([$("#mapContain").prop("clientWidth") / 2 + 200, pixel[1]]);
                            map.getView().setCenter(coordinate);
                        } else if (pixel[0] < 200) {
                            coordinate = map.getCoordinateFromPixel([$("#mapContain").prop("clientWidth") / 2 - 200, pixel[1]]);
                            map.getView().setCenter(coordinate);
                        } else if (pixel[1] < 200){
                            coordinate = map.getCoordinateFromPixel([pixel[0], $("#mapContain").prop("clientHeight") / 2 - 200]);
                            map.getView().setCenter(coordinate);
                        } else {
                            map.getView().setCenter(e.mapBrowserEvent.coordinate);
                        }
                    }
                });
                var wfsimage_hover = new ol.style.Icon({
                    src: '/ssjc/images/gis/marker.png',
                    scale: 0.8
                });
                var wfsstyle_hover = {
                    'Point': new ol.style.Style({
                        image: wfsimage_hover
                    }),
                    'MultiPoint': new ol.style.Style({
                        image: wfsimage_hover
                    }),
                    'LineString': new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#00FFFF',
                            width: 3
                        })
                    }),
                    'MultiLineString': new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#00FFFF',
                            width: 3
                        })
                    }),
                    'Polygon': new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#00FFFF',
                            lineDash: [4],
                            width: 3
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(0, 0, 255, 0.1)'
                        })
                    }),
                    'MultiPolygon': new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: '#00FFFF',
                            lineDash: [4],
                            width: 3
                        }),
                        fill: new ol.style.Fill({
                            color: 'rgba(0, 0, 255, 0.1)'
                        })
                    })
                };
                var pre;
                selectPointerMove.on("select", function(e) {
                    var hit = !!e.target.getFeatures().getLength();
                    map.getTargetElement().style.cursor = hit ? 'pointer' : 'default';
                    if (hit) {
                        if(data.query) {
                            pre && pre.setStyle(evaluationStyleFun[pre]);
                        }
                        else {
                            pre && pre.setStyle(WfsstyleFunction[pre]);
                        }
                        pre = e.target.getFeatures().array_[0];
                        pre.setStyle(wfsstyle_hover[pre.getGeometry().getType()]);
                    } else {
                        if(data.query) {
                            pre && pre.setStyle(evaluationStyleFun[pre]);
                        }
                        else {
                            pre && pre.setStyle(WfsstyleFunction[pre]);
                        }
                    }
                });
                break;
            }
            default : break;
        }
        return layer;
    }
    //符号组
    var wfsStyles = {
        '主干路': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'green',
                width: 1
            })
        }),
        '次干路':new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1
            })
        }),
        '支路': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 1
            })
        }),
        '高速公路': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'palegodenrod',
                width: 2
            })
        }),
        '街坊路': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'chartreuse',
                width: 1
            })
        }),
        '快速路': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'tan',
                width: 2
            })
        })
    };

    var evaluationStyles={
        'green': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'green',
                width: 2
            })
        }),
        'blue':new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'blue',
                width: 2
            })
        }),
        'yellow': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'yellow',
                width: 2
            })
        }),
        'red': new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: 'red',
                width: 2
            })
        })
    };
    //路网符号
    var WfsstyleFunction = function(feature) {
        return wfsStyles[feature.getProperties().class];
    };
    //路况符号
    var evaluationdata;
     var evaluationStyleFun=function(featrue){
          if(evaluationdata)
          {
              var roadecode=featrue.getProperties().hb_code;
              var featureRoadLevel="green";
              for(var i=0;i<evaluationdata.length;i++){
                if(roadecode==evaluationdata[i]["roadCode"])
                {
                     featureRoadLevel=evaluationdata[i]["grade"];
                    break;
                }
            }
              return evaluationStyles[featureRoadLevel];
          }
     };
    //轨迹回放
    function replayingrunningdata(data) {
        //通过地址请求数据
        $.get(url).then(function (response) {
            var format = new ol.format.GeoJSON();
            var features;

        })
    }

    var PagesData = Model.create();
    pages = PagesData.init();
    pages.save();
    PagesData.childId = pages.id;
    PagesData.event.on("create", function (e, data) {
        var ddData = Model.create();
        var dd = pages[data] || ddData.init({
                event: $({})
            });
        var o = {};
        o[data] = dd;
        if (!pages[data]) {
            pages.init(o);
            dd.init({
                buttonStat: {
                    "klass": "confirm",
                    "text": "查看"
                },
                input: {
                    "sYears": 2013,
                    "sMonth": 7,
                    "sDay": 26,
                    "eYears": 2013,
                    "eMonth": 7,
                    "eDay": 27,
                    "years": 2013,
                    "kpi": "PQI",
                    "charts": "饼状",
                    "selector": "公路桥梁",
                    "fromParam": "道路长度",
                    "type": "市政道路"
                },
                getValue: function () {
                    if (!this.condition) return;
                    var value = {};
                    for (var key in this.condition) {
                        if (key.indexOf("kpi") > -1 ) {
                            value["kpi"] = this.input["kpi"];
                        }
                        value[key] = this.condition.hasOwnProperty(key) && this.input[key];
                    }
                    return value;
                }
            });
            dd.event.on("loadLayer", function (e, data) {
                if (/*!data.query || */!data.url || !dd.canTrigger) return;
                access(data, dd, map);
            });
            dd.event.on("removeLayer", function (e, model) {
                model.canTrigger = false;
                var overlays = model.layer;
                if (!model.layer) return;
                var source = !model.layer.length && model.layer.getSource();
                if ($.isFunction(source.clear)) {
                    source.clear(false);
                    model.selectPointerMove && model.selectPointerMove.un("select");
                    model.selectClick && model.selectClick.un("select");
                    map.removeInteraction(model.selectPointerMove);
                    map.removeInteraction(model.selectClick);
                    var olay = $("#overlay").data("query");
                    olay && olay.setPosition([9999, 9999]);
                }
                if (overlays && overlays.length > 0) {
                    var length = overlays.length;
                    for (var i = 0; i < length; i += 1) {
                        var overlay = overlays[i];
                        var div = overlay.getElement();
                        $(div).off("mousedown");
                        $(div).off("mousewheel");
                        map.removeOverlay(overlay);
                    }
                    Message_bone.trigger("legendHide");
                    map.getLayers().getArray()[0].setOpacity("1");
                    model.lagendRenderdata.finish = false;
                }
                map.removeLayer(model.layer);
                model.buttonStat = {
                    "klass": "confirm",
                    "text": "查看"
                };
                Message_bone.trigger("removeLayer");
                Message_bone.trigger("removeQuery");
                Message_bone.trigger("closeButtonHide");
            })
        }
    });

    return {
        statistical: statistical,
        PagesData: PagesData,
        pages: pages
    };
});
